package org.abratuhi.kvngroupware.login.widget;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.Properties;

import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SpringLayout;
import javax.swing.SwingUtilities;

import org.abratuhi.kvngroupware.login.manager.LoginManager;
import org.abratuhi.kvngroupware.network.Message;
import org.abratuhi.kvngroupware.network.MessageSender;
import org.abratuhi.kvngroupware.spring.SpringUtilities;
import org.abratuhi.kvngroupware.widget.AbstractWorkWidget;
import org.jdom.Element;

@SuppressWarnings("serial")
public class GuiLogin extends AbstractWorkWidget{
	public final static String AC_LOGIN = "ac.login";
	public final static String AC_REGISTER = "ac.register";
	
	LoginManager loginmanager;
	
	JLabel labelId = new JLabel();
	JLabel labelPassword = new JLabel();
	JTextField fieldId = new JTextField();
	JPasswordField fieldPassword = new JPasswordField();
	JButton buttonRegistration = new JButton();
	JButton buttonLogin = new JButton();
	
	public GuiLogin(MessageSender sender, LoginManager loginmanager, Properties locale){
		super("", "KVNGroupware Client: Login", sender, locale);
		
		this.loginmanager = loginmanager;
		
		setLayout(new SpringLayout());
		setPreferredSize(new Dimension(200, 70));
		
		buttonLogin.setText(locale.getProperty("login.button.login"));
		buttonRegistration.setText(locale.getProperty("login.button.register"));
		labelId.setText(locale.getProperty("login.label.id"));
		labelPassword.setText(locale.getProperty("login.label.password"));
		
		buttonLogin.setAction(new LoginAction(locale.getProperty("login.button.login")));
		
		add(labelId);
		add(fieldId);
		add(labelPassword);
		add(fieldPassword);
		//add(buttonRegistration);
		add(new JLabel());
		add(buttonLogin);
		
		SpringUtilities.makeCompactGrid(this, 3, 2, 0, 0, 0, 0);
		
		revalidate();
	}
	
	public String[] getLoginData(){
		return new String[]{
				new String(fieldId.getText()),
				new String(fieldPassword.getPassword())
				};
	}
	
	public void clearLoginData(){
		fieldId.setText("");
		fieldPassword.setText("");
	}
	
	class LoginAction extends AbstractAction{
		public LoginAction(String text){
			super(text, null);
		}

		@Override
		public void actionPerformed(ActionEvent e) {
			String[] idpass = getLoginData();
			loginmanager.getUser().assignTempIdPassword(idpass[0], idpass[1]);
			sender.sendMessage(
					sender.createMessage(new String[]{"type","action"},
								new String[]{"user","login"},
								"",
								new Element[]{loginmanager.getUser().toElement()}));
		}
		
	}
}
